<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/27/027
 * Time: 15:51
 */

namespace App\Http\Traits;


use Illuminate\Support\Facades\Cache;

trait EloquentCacheTrait
{
    /**
     * @var int
     * 生命周期
     */
    protected $cacheLifeTime = 60;

    /**
     * @var bool
     *
     * 不是永久缓存
     */
    protected $isTimeAwareQuery = true;



    /**
     * @var
     *
     * 缓存句柄
     */
    protected $cache;


    /**
     * 重写启动脚本
     */
    public static function bootEloquentCacheTrait()
    {
        self::saved(function ($model) {
            if(!empty($model->tenant_id))
                $model->clearCache($model->tenant_id);
        });
        self::deleted(function ($model) {
            if(!empty($model->tenant_id))
                $model->clearCache($model->tenant_id);
        });
    }




    /**
     * @param array $fields
     * @param array $where
     * @param array $orderBy
     * @param array $groupBy
     *
     * 获取所有缓存数据
     */
    protected function getCacheAll($tenantId)
    {
        $cacheKey = $this->generateCacheKey($tenantId);

        if(Cache::has($cacheKey)) {
            return Cache::get($cacheKey);
        }
        if($this->isTimeAwareQuery) {
            return Cache::remember($cacheKey, $this->cacheLifeTime, function() use($tenantId){
                return static::where('tenant_id',$tenantId)->get();
            });
        } else {
            Cache::rememberForever($cacheKey, function() use($tenantId){
                return static::where('tenant_id',$tenantId)->get();
            });
        }

    }

    /**
     * 生成缓存key
     */
    protected function generateCacheKey($tenantId)
    {
        return sha1($this->getConnectionName() . $this->getTable(). $tenantId);
    }



    /**
     * 清除缓存项目
     * @return void
     */
    protected function clearCache($tenantId)
    {
        Cache::forget($this->generateCacheKey($tenantId));
    }
}